package com.jic.order.impl;

import com.jic.common.base.vo.RestResult;
import com.jic.order.entity.*;
import com.jic.order.enums.OrderStatusEnum;
import com.jic.order.manage.request.OrderInfoSetEditRequest;
import com.jic.order.manage.request.OrderInfoSetRequest;
import com.jic.order.mapper.OrderAfterSaleApplyMapper;
import com.jic.order.mapper.OrderMapper;
import com.jic.order.mapper.OrderParentMapper;
import com.jic.order.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单自动取消
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-02 11:03:54
 */
@Service
@Slf4j
public class OrderInfoSetServiceImpl implements OrderInfoSetService {
    @Autowired
    OrderAutomaticCancelService orderAutomaticCancelService;
    @Autowired
    OrderAutomaticReceiptedService orderAutomaticReceiptedService;
    @Autowired
    OrderAutomaticCompleteService orderAutomaticCompleteService;
    @Autowired
    OrderAutomaticAftersaleService orderAutomaticAftersaleService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderParentMapper orderParentMapper;
    @Autowired
    OrderAfterSaleApplyMapper orderAfterSaleApplyMapper;


    /**
     * 编辑订单信息设置
     * tabType 1 代表订单自动取消  2  代表自动签收  3代表自动完成 4售后单自动审核
     *
     * @param orderInfoSetEditRequest 订单信息设置编辑请求
     * @return {@link RestResult}
     */
    @Override
    public RestResult editOrderInfoSet(OrderInfoSetEditRequest orderInfoSetEditRequest) {
        RestResult restResult = new RestResult();
        if (orderInfoSetEditRequest.getTabType() == 1) {
            Long deptId = orderInfoSetEditRequest.getAdminOperate().getDeptId();
            orderInfoSetEditRequest.setDeptId(deptId);
            OrderAutomaticCancel orderAutomaticCancel = new OrderAutomaticCancel();
            BeanUtils.copyProperties(orderInfoSetEditRequest, orderAutomaticCancel);
            if (orderAutomaticCancel.getId() != null) {//修改
                OrderAutomaticCancel orderAutomaticCancelById = orderAutomaticCancelService.queryByPrimaryKey(orderAutomaticCancel.getId());//通过id 查询
                Boolean flagChannelId = orderAutomaticCancelById.getChannelId() == orderAutomaticCancel.getChannelId();
                Boolean flagOrderSource = orderAutomaticCancelById.getOrderSource() == orderAutomaticCancel.getOrderSource();
                Boolean flagPayType = orderAutomaticCancelById.getPayType() == orderAutomaticCancel.getPayType();
                if (flagChannelId && flagOrderSource && flagPayType) {
                    orderAutomaticCancelService.update(orderAutomaticCancel);
                    return RestResult.success(true);
                } else {
                    List<OrderAutomaticCancel> orderAutomaticCancelList = orderAutomaticCancelService.query(orderAutomaticCancel);
                    if (orderAutomaticCancelList.size() > 0) {
                        return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                    } else {
                        orderAutomaticCancelService.update(orderAutomaticCancel);
                        return RestResult.success(true);
                    }
                }
            } else {//新增
                //判断是否已经添加
                List<OrderAutomaticCancel> orderAutomaticCancelList = orderAutomaticCancelService.query(orderAutomaticCancel);
                if (orderAutomaticCancelList.size() > 0) {
                    return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                }
                orderAutomaticCancelService.insert(orderAutomaticCancel);
                return RestResult.success(true);
            }
        } else if (orderInfoSetEditRequest.getTabType() == 2) {
            OrderAutomaticReceipted orderAutomaticReceipted = new OrderAutomaticReceipted();
            BeanUtils.copyProperties(orderInfoSetEditRequest, orderAutomaticReceipted);
            if (orderAutomaticReceipted.getId() != null) {//修改
                OrderAutomaticReceipted orderAutomaticReceiptedById = orderAutomaticReceiptedService.queryByPrimaryKey(orderAutomaticReceipted.getId());//通过id 查询
                Boolean flagChannelId = orderAutomaticReceiptedById.getChannelId() == orderAutomaticReceipted.getChannelId();
                Boolean flagOrderSource = orderAutomaticReceiptedById.getOrderSource() == orderAutomaticReceipted.getOrderSource();
                Boolean flagPayType = orderAutomaticReceiptedById.getPayType() == orderAutomaticReceipted.getPayType();
                if (flagChannelId && flagOrderSource && flagPayType) {
                    orderAutomaticReceiptedService.update(orderAutomaticReceipted);
                    return RestResult.success(true);
                } else {
                    List<OrderAutomaticReceipted> orderAutomaticReceiptedList = orderAutomaticReceiptedService.query(orderAutomaticReceipted);
                    if (orderAutomaticReceiptedList.size() > 0) {
                        return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                    } else {
                        orderAutomaticReceiptedService.update(orderAutomaticReceipted);
                        return RestResult.success(true);
                    }
                }
            } else {//新增
                //判断是否已经添加
                List<OrderAutomaticReceipted> orderAutomaticReceiptedList = orderAutomaticReceiptedService.query(orderAutomaticReceipted);
                if (orderAutomaticReceiptedList.size() > 0) {
                    return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                }
                orderAutomaticReceiptedService.insert(orderAutomaticReceipted);
                return RestResult.success(true);
            }
        } else if (orderInfoSetEditRequest.getTabType() == 3) {
            OrderAutomaticComplete orderAutomaticComplete = new OrderAutomaticComplete();
            BeanUtils.copyProperties(orderInfoSetEditRequest, orderAutomaticComplete);
            if (orderAutomaticComplete.getId() != null) {//修改
                OrderAutomaticComplete orderAutomaticCompleteById = orderAutomaticCompleteService.queryByPrimaryKey(orderAutomaticComplete.getId());//通过id 查询
                Boolean flagChannelId = orderAutomaticCompleteById.getChannelId() == orderAutomaticComplete.getChannelId();
                Boolean flagOrderSource = orderAutomaticCompleteById.getOrderSource() == orderAutomaticComplete.getOrderSource();
                Boolean flagPayType = orderAutomaticCompleteById.getPayType() == orderAutomaticComplete.getPayType();
                if (flagChannelId && flagOrderSource && flagPayType) {
                    orderAutomaticCompleteService.update(orderAutomaticComplete);
                    return RestResult.success(true);
                } else {
                    List<OrderAutomaticComplete> orderAutomaticCompleteList = orderAutomaticCompleteService.query(orderAutomaticComplete);
                    if (orderAutomaticCompleteList.size() > 0) {
                        return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                    } else {
                        orderAutomaticCompleteService.update(orderAutomaticComplete);
                        return RestResult.success(true);
                    }
                }
            } else {//新增
                //判断是否已经添加
                List<OrderAutomaticComplete> orderAutomaticCompleteList = orderAutomaticCompleteService.query(orderAutomaticComplete);
                if (orderAutomaticCompleteList.size() > 0) {
                    return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                }
                orderAutomaticCompleteService.insert(orderAutomaticComplete);
                return RestResult.success(true);
            }
        } else {
            OrderAutomaticAftersale orderAutomaticAftersale = new OrderAutomaticAftersale();
            BeanUtils.copyProperties(orderInfoSetEditRequest, orderAutomaticAftersale);
            if (orderAutomaticAftersale.getId() != null) {//修改
                OrderAutomaticAftersale orderAutomaticAftersaleById = orderAutomaticAftersaleService.queryByPrimaryKey(orderAutomaticAftersale.getId());//通过id 查询
                Boolean flagChannelId = orderAutomaticAftersaleById.getChannelId() == orderAutomaticAftersale.getChannelId();
                Boolean flagOrderSource = orderAutomaticAftersaleById.getAftersaleType() == orderAutomaticAftersale.getAftersaleType();
                if (flagChannelId && flagOrderSource) {
                    orderAutomaticAftersaleService.update(orderAutomaticAftersale);
                    return RestResult.success(true);
                } else {
                    List<OrderAutomaticAftersale> orderAutomaticAftersaleList = orderAutomaticAftersaleService.query(orderAutomaticAftersale);
                    if (orderAutomaticAftersaleList.size() > 0) {
                        return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                    } else {
                        orderAutomaticAftersaleService.update(orderAutomaticAftersale);
                        return RestResult.success(true);
                    }
                }
            } else {//新增
                //判断是否已经添加
                List<OrderAutomaticAftersale> orderAutomaticAftersaleList = orderAutomaticAftersaleService.query(orderAutomaticAftersale);
                if (orderAutomaticAftersaleList.size() > 0) {
                    return RestResult.error("9999", "自动配置类型在订单自动配置中已被使用");
                }
                orderAutomaticAftersaleService.insert(orderAutomaticAftersale);
                return RestResult.success(true);
            }
        }

    }

    /**
     * 删除
     *
     * @param orderInfoSetRequest 订单信息设置请求
     * @return {@link RestResult}
     */
    @Override
    public RestResult delete(OrderInfoSetRequest orderInfoSetRequest) {
        String[] ids = orderInfoSetRequest.getIds().split(",");
        if (orderInfoSetRequest.getTabType() == 1) {//订单自动取消删除
            for (int i = 0; i < ids.length; i++) {
                orderAutomaticCancelService.delete(Long.valueOf(ids[i]));
            }
        } else if (orderInfoSetRequest.getTabType() == 2) {//订单自动签收删除
            for (int i = 0; i < ids.length; i++) {
                orderAutomaticReceiptedService.delete(Long.valueOf(ids[i]));
            }
        } else if (orderInfoSetRequest.getTabType() == 3) {//订单自动完成删除
            for (int i = 0; i < ids.length; i++) {
                orderAutomaticCompleteService.delete(Long.valueOf(ids[i]));
            }
        } else if (orderInfoSetRequest.getTabType() == 4) {//售后单自动审核删除
            for (int i = 0; i < ids.length; i++) {
                orderAutomaticAftersaleService.delete(Long.valueOf(ids[i]));
            }
        }
        return RestResult.success(true);
    }

    /**
     * 及时、定期订货
     * 定时订单实时效性
     *
     * @return {@link RestResult<String>}
     */
    @Override
    public RestResult<String> regularOrdersTimely() {
        log.info("订单时效性定时任务开始===================start");
        //取消订单
        this.cancelOrder();
        //订单自动签收
        this.ordersAutomaticallySign();
        //订单自动完成
        this.orderCompletion();
        //售后单自动审核
        this.afterASingleAutomaticReview();
        log.info("订单时效性定时任务开始===================end");
        return null;
    }
    /**
     * 取消订单
     */
    private void cancelOrder() {
        //订单自动取消
        List<OrderAutomaticCancel> orderAutomaticCancelList = orderAutomaticCancelService.query(new OrderAutomaticCancel());
        if (CollectionUtils.isNotEmpty(orderAutomaticCancelList)) {
            orderAutomaticCancelList.forEach(orderAutomaticCancel -> {
                //查询待支付订单
                List<OrderParent> orderParentList = orderParentMapper.query(new OrderParent() {{
                    setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
                    setSaleChannel(orderAutomaticCancel.getChannelId().intValue());
                }});
                //更新订单
                generalOrderUpdate(orderParentList, OrderStatusEnum.CLOSED.getCode(), orderAutomaticCancel.getCancelTime());
            });
        }
    }

    /**
     * 订单自动签收
     */
    private void ordersAutomaticallySign() {
        List<OrderAutomaticReceipted> orderAutomaticReceiptedList = orderAutomaticReceiptedService.
                query(new OrderAutomaticReceipted());
        if (CollectionUtils.isNotEmpty(orderAutomaticReceiptedList)) {
            orderAutomaticReceiptedList.forEach(orderAutomaticReceipted -> {
                //查询待支付订单
                List<OrderParent> orderParentList = orderParentMapper.query(new OrderParent() {{
                    setOrderStatus(OrderStatusEnum.ALREADY_SHIP.getCode());
                    setSaleChannel(orderAutomaticReceipted.getChannelId().intValue());
                }});
                //更新订单
                generalOrderUpdate(orderParentList, OrderStatusEnum.CONFIRM_SHIP.getCode(),
                        orderAutomaticReceipted.getCancelTime());
            });
        }
    }

    /**
     * 订单自动完成
     */
    private void orderCompletion() {
        List<OrderAutomaticComplete> orderAutomaticCompleteList = orderAutomaticCompleteService.
                query(new OrderAutomaticComplete());
        if (CollectionUtils.isNotEmpty(orderAutomaticCompleteList)) {
            orderAutomaticCompleteList.forEach(orderAutomaticComplete -> {
                //查询待支付订单
                List<OrderParent> orderParentList = orderParentMapper.query(new OrderParent() {{
                    setOrderStatus(OrderStatusEnum.CONFIRM_SHIP.getCode());
                    setSaleChannel(orderAutomaticComplete.getChannelId().intValue());
                }});
                //更新订单
                generalOrderUpdate(orderParentList, OrderStatusEnum.WAIT_REVIEW.getCode(),
                        orderAutomaticComplete.getCancelTime());
            });
        }
    }

    /**
     * 售后单自动审核
     */
    private void afterASingleAutomaticReview() {
        //查询售后单自动审核
        List<OrderAutomaticAftersale> orderAutomaticAftersaleList = orderAutomaticAftersaleService.
                query(new OrderAutomaticAftersale());
        if (CollectionUtils.isNotEmpty(orderAutomaticAftersaleList)) {
            List<OrderAfterSaleApplyModel> orderAfterSaleApplyModelList = orderAfterSaleApplyMapper.
                    queryByAll(new OrderAfterSaleApplyModel() {{
                        setStatus(1010);
                        setDeleteFlag(0);
                    }});
            orderAutomaticAftersaleList.forEach(orderAutomaticAftersale -> {
                if (CollectionUtils.isNotEmpty(orderAfterSaleApplyModelList)) {
                    orderAfterSaleApplyModelList.forEach(orderAfterSaleApplyModel -> {
                        //售后类型 1仅退款未发货，2仅退款已发货，3退款退货
                        if (orderAutomaticAftersale.getAftersaleType().intValue() ==
                                orderAfterSaleApplyModel.getAfterSaleType()) {
                            orderAfterSaleApplyModel.setStatus(1030);
                            orderAfterSaleApplyMapper.updateAfterSale(orderAfterSaleApplyModel);
                        }
                    });
                }
            });
        }
    }

    /**
     * 订单更新
     *
     * @param orderParentList 以父列表
     * @param orderStatus     订单状态
     */
    private void generalOrderUpdate(List<OrderParent> orderParentList, Integer orderStatus, Long cancelTime) {
        orderParentList.forEach(orderParent -> {
            Long min = getMin(orderParent.getCreateTime());
            if (min >= cancelTime) {
                //更新订单 关闭状态
                orderParent.setOrderStatus(orderStatus);
                orderParentMapper.update(orderParent);
            }
        });
    }

    /**
     * 得到最小值
     * 判读时间差距，两个时间相差多少天，时，分，秒
     *
     * @param date 日期
     * @return {@link Long}
     */
    public static Long getMin(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long diff = null;
        try {
            long NTime = df.parse(df.format(new Date())).getTime();
            //从对象中拿到时间
            long OTime = df.parse(df.format(date)).getTime();
            diff = (NTime - OTime) / 1000 / 60;
        } catch (ParseException e) {
            log.error("时间转化异常:{}", e);
        }
        return diff;
    }
}
